<template>
  <BasicModal
    v-bind="$attrs"
    @register="register"
    :title="displayModuleTitle"
    @ok="onOkButtonClick"
    @cancel="resetField"
    width="1100px"
  >
    <div style="width: 100%; display: flex">
      <a-form
        style="width: 60%; border-right: 1px solid #ddd"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 14 }"
      >
        <a-form-item
          :label-col="{ span: 4 }"
          :wrapper-col="{ span: 19 }"
          style="margin-bottom: 15px"
          label="检查项内容"
          :required="true"
        >
          <a-textarea
            v-model:value="checkItemList"
            @change="checkItemListChange"
            placeholder="用一个或多个空行分隔多个检查项；
每个检查项第一个换行前的内容是检查项的标题；
检查项标题后的所有内容是待选项，待选项间使用换行分隔；"
            :auto-size="{ minRows: 12, maxRows: 12 }"
          />
        </a-form-item>
        <a-row>
          <a-col :span="12">
            <a-form-item style="margin-bottom: 15px" label="是否必填" :required="true">
              <a-radio-group v-model:value="batchAddFormData.notnull">
                <a-radio :value="true">是</a-radio>
                <a-radio :value="false">否</a-radio>
              </a-radio-group>
            </a-form-item></a-col
          >
          <a-col :span="12">
            <a-form-item style="margin-bottom: 15px" label="填写文本类型">
              <a-select v-model:value="batchAddFormData.contenttype">
                <a-select-option :value="1">始终必填</a-select-option>
                <a-select-option :value="2">始终不填</a-select-option>
                <a-select-option :value="3">为异常时填写</a-select-option>
              </a-select>
            </a-form-item></a-col
          >
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item style="margin-bottom: 15px" label="最少图片数量">
              <a-input-number v-model:value="batchAddFormData.minimgcount" :min="0" /> </a-form-item
          ></a-col>
          <a-col :span="12"
            ><a-form-item style="margin-bottom: 15px" label="默认选项配置">
              <a-radio-group
                :options="defaultOption"
                v-model:value="chooseDefaultOption"
                @change="chooseDefaultOptionChange"
              >
              </a-radio-group> </a-form-item
          ></a-col>
        </a-row>
      </a-form>
      <div style="width: 40%; padding: 8px; max-height: 400px; overflow-y: auto">
        <a-empty v-if="formatCheckItemList?.length < 1" description="暂无可预览配置" />
        <a-form v-else>
          <a-form-item
            v-for="(item, index) in formatCheckItemList"
            :required="batchAddFormData.notnull"
            :wrapperCol="{ span: 22 }"
          >
            <a-row class="mb-1">
              <a-col>
                <span v-if="batchAddFormData.notnull" style="color: red; margin-right: 5px">*</span>
                <label :for="item.field">{{ index + 1 }}. {{ item.title }}</label>
              </a-col>
            </a-row>

            <a-radio-group
              style="margin-bottom: 10px"
              v-model:value="checkResult[item.title].value"
              :options="item.options"
            ></a-radio-group>

            <a-input
              style="margin-bottom: 5px"
              v-show="
                batchAddFormData.contenttype == 1 ||
                (batchAddFormData.contenttype == 3 &&
                  checkResult[item.title].value == item.options[item.options.length - 1].value)
              "
              v-model:value="checkResult[item.title].description"
            />
            <BasicUpload
              style="margin-top: 5px"
              v-if="
                batchAddFormData.minimgcount &&
                (batchAddFormData.contenttype == 1 ||
                  (batchAddFormData.contenttype == 3 &&
                    checkResult[item.title].value == item.options[item.options.length - 1].value))
              "
              :maxSize="1024"
              :multiple="true"
              v-model:value="checkResult[item.title].images"
              :api="uploadApi"
              :uploadParams="{ system: 'ehs', module: 'attachment', title: '' }"
              :showPreviewNumber="true"
              :showUploadList="{
                showPreviewIcon: true,
                showRemoveIcon: true,
                showDownloadIcon: false,
              }"
            />
          </a-form-item>
        </a-form>
      </div>
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { computed, defineComponent, ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { displayTitle } from '/@/utils/QcUnifyUtil';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { batchAddCheckItem } from '/@/api/ehs/checkForm';
  import { BasicUpload } from '/@/components/Upload';
  import { uploadApi } from '/@/api/platform/upload';
  const { createMessage } = useMessage();
  export default defineComponent({
    components: { BasicModal, BasicForm, BasicUpload },
    name: 'BulkAddCheckItem',
    emits: ['success'],
    setup(_, { emit }) {
      const operateType = ref(OperationTypeEnum.UN_KNOWN);
      const qcUnifyProps = ref<QcUnifyTransToChildProps>();
      const groupid = ref();
      const tableid = ref();
      const defaultOption = ['是,否', '正常,异常'];
      const chooseDefaultOption = ref('是,否');
      /**
       * 文本域输入内容
       */
      const checkItemList = ref([]);
      /**
       * 格式化后用来预览显示的数据
       */
      const formatCheckItemList = ref([]);
      const batchAddFormData = ref({
        notnull: true,
        contenttype: 3,
        minimgcount: 0,
        title: [],
        options: [],
      });
      const checkResult = ref({});
      const [register, { closeModal }] = useModalInner((data) => {
        if (data != undefined && data != null) {
          let unrefData = unref(data);
          qcUnifyProps.value = unrefData;
          //接收父组件传递的数据
          if (unrefData?.operateType) {
            //判断是否传入op属性
            operateType.value = unrefData.operateType;
          }
          tableid.value = unrefData.tableid;
          groupid.value = unrefData.groupid;
        }
      });
      function onOkButtonClick() {
        if (formatCheckItemList.value?.length < 1) {
          return createMessage.error('请配置至少一条检查项, 当前输入配置为空!');
        }
        let params = {
          ...batchAddFormData.value,
          tableid: tableid.value,
          groupid: groupid.value,
          title: formatCheckItemList.value.map((item) => item.title),
          options: formatCheckItemList.value.map((item) => JSON.stringify(item.options)),
        };
        console.log(params, 'params');
        batchAddCheckItem(params).then((res) => {
          if (!res) {
            createMessage.success('批量添加成功');
            emit('success');
            resetField();
          } else {
            createMessage.error('添加失败,请稍后重试!');
          }
        });
      }

      /**
       * 当输入的配置项改变时，格式化数据并显示
       */
      function checkItemListChange(e) {
        formatCheckItem(e.target.value);
      }

      /*
       * 选择的默认选项更改时, 重新格式化
       */
      function chooseDefaultOptionChange(e) {
        formatCheckItem(checkItemList.value);
      }

      /**
       * 格式化操作
       */
      function formatCheckItem(data) {
        let arr = [];
        checkResult.value = {};
        if (data) {
          // 根据空行切割e字符串, 不确定有几个空行，所以用split分割
          let arr1 = data.split(/\n\s*\n/).filter((item) => item);
          // console.log(arr1, 'arr1');
          // 遍历arr1，将每个元素根据换行符切割，第一个是标题，后面的都是选项
          for (let i = 0; i < arr1.length; i++) {
            let arr2 = arr1[i].split(/\n/).filter((item) => item); // 分割标题和选项
            // console.log(arr2, 'arr2');
            let title = arr2[0];
            // 选项
            let options = arr2.slice(1);
            // 将标题和选项放入对象中
            let obj = {
              title: title,
              options:
                options?.length > 0
                  ? options.map((item) => {
                      return {
                        label: item,
                        value: item,
                      };
                    })
                  : chooseDefaultOption.value.split(',').map((item) => {
                      return {
                        label: item,
                        value: item,
                      };
                    }),
            };
            // 将对象放入数组中
            arr.push(obj);
            checkResult.value[title] = {
              value: '',
              description: '',
              images: [],
            };
          }
        }

        console.log(arr, 'arr');
        console.log(checkResult.value, 'checkResult.value');
        formatCheckItemList.value = arr;
      }

      let displayModuleTitle = computed(() => {
        return displayTitle(qcUnifyProps.value);
      });

      function resetField() {
        batchAddFormData.value = {
          notnull: true,
          contenttype: 3,
          minimgcount: 0,
          title: [],
          options: [],
        };
        checkItemList.value = [];
        formatCheckItemList.value = [];
        checkResult.value = {};
        chooseDefaultOption.value = '是,否';
        closeModal();
      }
      return {
        uploadApi,
        register,
        defaultOption,
        chooseDefaultOption,
        displayModuleTitle,
        onOkButtonClick,
        checkItemList,
        formatCheckItemList,
        batchAddFormData,
        checkItemListChange,
        chooseDefaultOptionChange,
        checkResult,
        resetField,
      };
    },
  });
</script>
